package com.neolix.watch.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;

import com.neolix.watch.NeolixApplication;
import com.neolix.watch.R;

import static android.media.AudioManager.STREAM_MUSIC;

public class AudioPlayerService extends Service {
    private final static String TAG = AudioPlayerService.class.getSimpleName();
    private static final String AUDIO_PLAYER_THREAD = "audioPlayerThread";

    private MediaPlayer mediaPlayer;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        adjustVolume(NeolixApplication.getInstance());
        this.mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.beep);
        mediaPlayer.setLooping(true);
        mediaPlayer.setAudioStreamType(STREAM_MUSIC);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, final int startId) {
//        Runnable runnable = new Runnable() {
//            @Override
//            public void run() {
//                play();
//            }
//        };
        play();
        return super.onStartCommand(intent, flags, startId);
    }

    private void play() {
        mediaPlayer.seekTo(0);
        mediaPlayer.start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (mediaPlayer != null) {
            release();
            mediaPlayer = null;
        }

        Log.i(TAG, "onDestroy");
    }

    private void release() {
        mediaPlayer.stop();
        mediaPlayer.release();

        mediaPlayer = null;
    }

    private void adjustVolume(NeolixApplication applicationContext) {
        AudioManager am = (AudioManager) applicationContext.getSystemService(Context.AUDIO_SERVICE);
        int maxVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        am.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume - 2, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
    }
}
